class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        vector<vector<int>> rst;
        if(nums.size() < 4){
            return rst;
        }
        sort(nums.begin(), nums.end());
        for(int i = 0; i < nums.size() - 3; ++i){
            if(i != 0 && nums[i] == nums[i - 1]){
                continue;
            }

            for(int j = nums.size() - 1; j > i + 2; --j){
                if(j != nums.size() - 1 && nums[j] == nums[j + 1]){
                    continue;
                }

                int left = i + 1;
                int right = j - 1;

                
                while(left < right){
                    long long int num = (long)nums[left] + nums[right] + nums[i] + nums[j];
                    if (num == target) {
                        rst.push_back({nums[i], nums[left], nums[right], nums[j]});
                    }

                    if(num < target){
                        do{
                            ++left;
                        } while(left < right && nums[left] == nums[left - 1]);
                    } else {
                        do{
                            right--;
                        } while(left < right && nums[right] == nums[right + 1]);
                    }
                }
            }
        }

        return rst;
    }
};
